#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include <cstdlib>
#include <ctime>

// 共享资源

int data = 0;
pthread_rwlock_t rwlock;

void *Reader(void *args)
{
    const char *name = static_cast<const char *>(args);
    while (true)
    {
        pthread_rwlock_rdlock(&rwlock);
        std::cout << name << " 正在读取数据，数据是： " << data << "\n";
        sleep(2);
        pthread_rwlock_unlock(&rwlock);
    }
}
void *Writer(void *args)
{
    const char *name = static_cast<const char *>(args);
    while (true)
    {
        pthread_rwlock_wrlock(&rwlock);
        data = rand() ^ getpid() % 10000;
        std::cout << name << " 正在写入数据，数据是: " << data << "\n";
        sleep(2);
        pthread_rwlock_unlock(&rwlock);
    }
}

int main()
{
    pthread_rwlock_init(&rwlock, nullptr);

    int r = 2;
    int w = 10;
    pthread_t reader[r];
    pthread_t writer[w];
    for (int i = 0; i < r; i++)
    {
        char *name = new char[128];
        snprintf(name,128,"reader thread - %d ",i+1);

        pthread_create(reader + i, nullptr, Reader, (void *)name);
    }
    for (int i = 0; i < w; i++)
    {
        char *name = new char[128];
        snprintf(name,128,"writer thread - %d ",i+1);
        pthread_create(writer + i, nullptr, Writer, (void *)name);
    }

    for (int i = 0; i < w; i++)
    {
        pthread_join(reader[i], nullptr);
        pthread_join(writer[i], nullptr);
    }

    pthread_rwlock_destroy(&rwlock);
    return 0;
}